< Bonus Materials I | Contents >
Vectorised backtesting
In [1]:
import numpy as np
import pandas as pd
import oandapy
import configparser
%matplotlib inline
import seaborn as sns
import matplotlib.pyplot as plt
config = configparser.ConfigParser()
config.read('../config/config_v1.ini')
account_id = config['oanda']['account_id']
api_key = config['oanda']['api_key']
oanda = oandapy.API(environment="practice",
access_token=api_key)
In [2]:
response = oanda.get_history(instrument="EUR_USD",
granularity="H1",
count = 5000)
In [3]:
res = pd.DataFrame(response['candles'])
res.columns = ['Close_Ask', 'Close_Bid', 'Complete',
'High_Ask', 'High_Bid', 'Low_Ask', 'Low_Bid',
'Open_Ask', 'Open_Bid', 'Time', 'Volume']
res = res.reindex_axis(['Time', 'Open_Bid', 'Open_Ask',
'High_Bid', 'High_Ask', 'Low_Bid',
'Low_Ask', 'Close_Bid', 'Close_Ask',
'Complete', 'Volume'],
axis=1)
In [4]:
df = res[['Time', 'Close_Bid', 'Close_Ask']].copy()
df['rtns'] = res['Close_Bid'].pct_change()
In [5]:
dtrain = df[0:4500].copy()
dtest = df[4500:].copy()
In [6]:
k = range(1,13)
h = 1
In [7]:
for oo in k:
dtrain['signal'] = np.sign(dtrain['rtns'].rolling(oo).sum())
dtrain['strategy_rtn'] = dtrain['signal'].shift(1) * dtrain['rtns']
res = dtrain['strategy_rtn'].dropna().sum()
print('{0:3} {1:>8.4f}'.format(oo, res))
In [8]:
dtest['signal'] = np.sign(dtest['rtns'].rolling(11).sum())
dtest['result'] = dtest['signal'].shift(1) * dtest['rtns']
dtest['result'].dropna().cumsum().plot(figsize=(10,6));
In [9]:
dtest['signal'] = - np.sign(dtest['rtns'].rolling(3).sum())
dtest['result'] = dtest['signal'].shift(1) * dtest['rtns']
dtest['result'].dropna().cumsum().plot(figsize=(10,6));
< Bonus Materials I | Contents >